<?php

namespace app\aiapi\controller;

/*
 * 百度AI接口图像识别
 *
 * */

use think\facade\Request;

class Vehicle
{

    protected $access_token;

    /**
     * client_id:百度ai控制台获取
     * client_secret:百度ai控制台获取秘钥
     */
    public function __construct()
    {
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = 'RnK4H2zEtRUXhQMaXXSY1rLf';
        $post_data['client_secret'] = 'uBKE4g8A5001jGCdibrLTaasraRsK6TF';
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $res = http_post($url, $post_data);
        $res = json_decode($res);
        $this -> access_token = $res -> access_token;
    }



    public function vehicleCar()
    {
        $type = Request::instance() -> post('type');
        $img = $_FILES["image"];
        $imgName = explode(".",$img["name"]);
        $imgArray = ['jpg','bmp','png'];
        if (!in_array($imgName[1],$imgArray)){
            return error("图片格式不支持");
        }
        $token = $this -> access_token;
        if ($type == 1)
        {
            $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/car?access_token=' . $token;
        }else if ($type == 2)
        {
            $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/vehicle_damage?access_token=' . $token;
        }
        $img = base64EncodeImage($img["tmp_name"]);
        $img = str_replace(PHP_EOL, '', $img);
        $bodys = array(
            'image' => $img,
        );
        $header["Content-Type"] = "application/x-www-form-urlencoded";
        $res = http_post($url, $header,$bodys);
        $res = json_decode($res);
        return success($res);

    }

}